import Cocoa
import SwiftUI

class AppDelegate: NSObject, NSApplicationDelegate {
    var statusBar: NSStatusItem!
    var popover: NSPopover!

    func applicationDidFinishLaunching(_ notification: Notification) {
        // Create the status bar item
        statusBar = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
        if let button = statusBar.button {
            button.title = "Xuanji"
        }

        // Initialize popover
        popover = NSPopover()
        popover.contentViewController = NSHostingController(rootView: ContentView())

        // Set up the action for when the status bar button is clicked
        statusBar.button?.action = #selector(togglePopover)
    }

    @objc func togglePopover() {
        // Ensure that the popover is toggled only once at a time
        if popover.isShown {
            popover.performClose(nil)
        } else {
            popover.show(relativeTo: statusBar.button!.bounds, of: statusBar.button!, preferredEdge: .maxY)
        }
    }
}
